package com.lqian.demo02.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author：Melody_LQ
 * @time：2022/7/13 1:50 下午
 */
public class JDBCUtils {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        try{
            //读取db.properties文件中的数据库连接信息
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties prop = new Properties();
            prop.load(is);

            //获取数据库连接驱动
            driver = prop.getProperty("driver");
            //获取数据库连接URL地址
            url = prop.getProperty("url");
            //获取数据库连接用户名
            username = prop.getProperty("username");
            //获取数据库连接密码
            password = prop.getProperty("password");

            //加载数据库驱动
            Class.forName(driver);
        }catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    // 获取数据库连接对象
    public static Connection getConnection() throws SQLException {

        return DriverManager.getConnection(url,username,password);
    }

    //释放资源
    //要释放的资源包括Connection数据库连接对象，负责执行SQL命令的Statement 对象，存储查询结果的ResultSet对象
    public static void release(Connection conn, Statement st, ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            rs = null; //help GC
        }
        if (st!=null){
            try {
                st.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            st = null; //help GC
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            conn = null; //help GC
        }
    }

    //When a Statement object is closed, its current
    // ResultSet object, if one exists, is also closed.
    public static void release(Connection conn, Statement st){
        if (st!=null){
            try {
                st.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            st = null; //help GC
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            conn = null; //help GC
        }
    }



}
